package net.tycmc.cty.ctyms.timejob.common;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.tycmc.bulb.common.util.MapGetter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * Map与XML相互转换
 * @author chengshichao
 *
 */
public class Map2XML {
	
	/**
	 * 将Map转换为XML字符串
	 * 目前支持Map最简单的【key，value】，value一般为String类型
	 * @param map
	 * @return
	 */
	public static String map2XMLStr(Map<String,Object> map,String rootName){
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement(rootName)
			.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
			.addAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
		Set<String> keySet = map.keySet();
		for(String key:keySet){
			root.addElement(key).addText(MapGetter.getString(map, key));
		}
		return document.asXML();
	}
	
	/**
	 * 将XML字符串转换为Map
	 * 目前支持Map最简单的【key，value】，value一般为String类型
	 * @param xmlStr
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,Object> xml2Map(String xmlStr){
		Map<String,Object> map = null;
		try {
			map = new HashMap<String,Object>();
			Document document = DocumentHelper.parseText(xmlStr);
			Element root = document.getRootElement();
			for (Iterator<Element> i = root.elementIterator(); i.hasNext(); ) {
				Element element = (Element) i.next();
				map.put(element.getName(), element.getText());
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}
}
